--全搬过去好麻烦，暂时把逻辑放scene上
local layer = require("GameLayer"):create()

local GameScene = class("GameScene", cc.Scene)

function GameScene:ctor()
    self:enableNodeEvents()
end

function GameScene:onEnter()
    layer:setPosition(0, 0)
    self:addChild(layer, GameBoardLevel)
    self:init()
    self:Mapinit()
    self:drawGameBoard()
    if layer:hasEliminate() then
        layer:findEliminate()
    else
        print("无需消除")
    end
end

function GameScene:onExit()

end

function GameScene:init()
    cclog("GameScene init")

    --菜单背景
    local sprite = cc.Sprite:create("images/game_bg.jpg")
    sprite:setPosition(display.center)
    sprite:setContentSize(size.height * 9 / 16, size.height)
    self:addChild(sprite, BackGroundLevel)

end

function GameScene:Mapinit()

    --游戏地图初始化为二维矩阵
    for i = 1, RowNum do
        local line_elements = {}
        for j = 1, ColNum do
            local element = require("Element.lua"):create()
            element.marked = false
            element.etype = ElementEliminateType
            line_elements[j] = element
        end
        gameBoard[i] = line_elements
    end
end

function GameScene:test()
    print("test")
end

function GameScene:fillGameBoard(row, col)
    --递归停止条件
    if row == 0 or row == RowNum + 1 or col == 0 or col == ColNum + 1 or gameBoard[row][col].etype ~= ElementEliminateType then
        return
    end

    local random_type = math.random(1, 6)

    gameBoard[row][col].etype = random_type

    --递归
    self:fillGameBoard(row + 1, col)
    self:fillGameBoard(row - 1, col)
    self:fillGameBoard(row, col + 1)
    self:fillGameBoard(row, col - 1)
end

function GameScene:drawGameBoard()
    math.randomseed(os.time())

    --生成内存地图
    self:fillGameBoard(1, 1)

    while(layer:hasEliminate()) do
        self:Mapinit()
        self:fillGameBoard(1,1)
    end


    --绘制地图
    for i = 1, RowNum do
        for j = 1, ColNum do
            local sprite
            if gameBoard[i][j].etype < 7 then
                local tp = ELementImgArray[gameBoard[i][j].etype]
                sprite = cc.Sprite:create(tp)
            else
                sprite = cc.Sprite:create("images/star.png")
            end
            sprite:setContentSize(element_size, element_size)
            local real_position = (cc.p(LeftMargin + (j - 0.5) * element_size, BottonMargin + (i - 0.5) * element_size))
            sprite:setPosition(real_position)
            sprite:setName(string.format("%d_%d", i, j))
            --绑定触摸事件
            layer:addChild(sprite, GameBoardLevel)
        end
    end
end



return GameScene